package com.hellobike.haxing.modules.wms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.dto.DeliveryOrderHeaderDto;
import com.hellobike.haxing.modules.wms.dto.ExportShippingShopPdfDto;
import com.hellobike.haxing.modules.wms.dto.ExportShippingUserInfoDto;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderDetail;
import com.hellobike.haxing.modules.wms.entity.DeliveryOrderHeader;
import com.hellobike.haxing.modules.wms.enums.DeliveryOrderStatusEnum;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsDeliveryFacade;
import com.hellobike.haxing.modules.wms.facade.WmsSyncFacade;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderDetailService;
import com.hellobike.haxing.modules.wms.service.IDeliveryOrderHeaderService;
import com.hellobike.haxing.modules.wms.utils.FileUtil;
import com.hellobike.haxing.modules.wms.utils.HtmlToPdf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: t_wms_delivery_order_header
 * @Author: haxing-boot
 * @Date: 2020-01-14
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wms/deliveryOrderHeader")
@Slf4j
public class DeliveryOrderHeaderController extends WmsBaseController<DeliveryOrderHeader, IDeliveryOrderHeaderService> {
    @Autowired
    private IDeliveryOrderHeaderService deliveryOrderHeaderService;

    @Autowired
    private WmsDeliveryFacade wmsDeliveryFacade;
    @Autowired
    private WmsSyncFacade wmsSyncFacade;
    @Autowired
    private IDeliveryOrderDetailService deliveryOrderDetailService;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 分页列表查询
     *
     * @param deliveryOrderHeader
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(DeliveryOrderHeader deliveryOrderHeader,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        deliveryOrderHeader.setWarehouseId(getWarehouseId());
        QueryWrapper<DeliveryOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(deliveryOrderHeader, req.getParameterMap());
        Page<DeliveryOrderHeader> page = new Page<DeliveryOrderHeader>(pageNo, pageSize);
        page.addOrder(OrderItem.desc("id"));
        IPage<DeliveryOrderHeader> pageList = deliveryOrderHeaderService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param deliveryOrderHeader
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DeliveryOrderHeader deliveryOrderHeader) {
        deliveryOrderHeaderService.save(deliveryOrderHeader);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param deliveryOrderHeader
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody DeliveryOrderHeader deliveryOrderHeader) {
        deliveryOrderHeaderService.updateById(deliveryOrderHeader);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        deliveryOrderHeaderService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.deliveryOrderHeaderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DeliveryOrderHeader deliveryOrderHeader = deliveryOrderHeaderService.getById(id);
        if (deliveryOrderHeader == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(deliveryOrderHeader);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param deliveryOrderHeader
     */
    @AutoLog(value = "t_wms_delivery_order_header-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DeliveryOrderHeader deliveryOrderHeader) {
        return super.exportXls(request, deliveryOrderHeader, DeliveryOrderHeader.class, "t_wms_delivery_order_header");
    }


    /**
     * 导出excel
     *
     */
    @AutoLog(value = "t_wms_asn_header-导出excel",operateType=6)
    @RequestMapping(value = "/exportUserInfo")
    public ModelAndView exportUserInfo(@RequestParam Long id) throws WmsExportException {
        try {
            DeliveryOrderHeader orderHeader = deliveryOrderHeaderService.getById(id);
            String title = "用户-"+orderHeader.getOrderCode();
            List<ExportShippingUserInfoDto> exportList = wmsExportFacade.exportUserInfo(id);
            return export(title,ExportShippingUserInfoDto.class,exportList);
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }


    @AutoLog(value = "t_wms_asn_header-导出pdf", operateType = 6)
    @RequestMapping(value = "/download")
    public void download(@RequestParam String idStr, HttpServletResponse response) throws WmsServiceException, WmsExportException {
        try {
            String filename = RandomStringUtils.random(12, false, true) + ".pdf";
            String type = new MimetypesFileTypeMap().getContentType(filename);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type", type);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            Context context = new Context();  //thymeleaf包下的
            Map<String, Object> map = new HashMap<>();
            List<ExportShippingShopPdfDto> list = wmsExportFacade.exportShippInfo(idStr);
            log.info("{}", JSON.toJSONString(list));
            map.put("shopPoList", list);
            context.setVariables(map);
            String html = templateEngine.process("shop_print", context);
            try {
                log.info(html);
                HtmlToPdf.topdf(html, "/tmp/" + filename);
                FileUtil.download("/tmp/" + filename, response);
            } catch (Exception ex) {
                log.error("", ex);
            }
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "t_wms_delivery_order_header-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DeliveryOrderHeader.class);
    }


    @AutoLog(value = "t_wms_delivery_order_header-createDOPick", operateType = 5)
    @RequestMapping(value = "/createDOPick", method = RequestMethod.POST)
    public Result<?> createDOPick(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        log.info(param.toString());
        try {
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsDeliveryFacade.batchCreateDOPickTask(ids, getWarehouseId(), getSysUserId());
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    @AutoLog(value = "t_wms_delivery_order_header-createWave", operateType = 5)
    @RequestMapping(value = "/createWave", method = RequestMethod.POST)
    public Result<?> createWave(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        log.info(param.toString());
        try {
            List<Long> ids = param.getJSONArray("ids").toJavaList(Long.class);
            wmsDeliveryFacade.createWave(ids, getWarehouseId(), getSysUserId());
        } catch (WmsServiceException e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    @AutoLog(value = "t_wms_delivery_order_header-分页列表查询")
    @GetMapping(value = "/queryPickedPageList")
    public Result<?> queryPickedPageList(DeliveryOrderHeader deliveryOrderHeader,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        deliveryOrderHeader.setWarehouseId(getWarehouseId());
        deliveryOrderHeader.setOrderStatus(DeliveryOrderStatusEnum.PICKED.getValue());
        QueryWrapper<DeliveryOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(deliveryOrderHeader, req.getParameterMap());
        Page<DeliveryOrderHeader> page = new Page<>(pageNo, pageSize);
        IPage<DeliveryOrderHeader> pageList = deliveryOrderHeaderService.page(page, queryWrapper);
        IPage<DeliveryOrderHeaderDto> result = wmsDeliveryFacade.wrapperPickInfo(pageList);
        return Result.ok(result);
    }


    @RequestMapping(value = "/getDetails", method = RequestMethod.POST)
    public Result<?> getDetails(@RequestBody JSONObject param, HttpServletRequest request, HttpServletResponse response) {
        log.info(param.toString());
        Long id = param.getLong("id");
        List<DeliveryOrderDetail> details = deliveryOrderDetailService.getByHeaderId(id);
        return Result.ok(details);
    }


    @RequestMapping(value = "/sync", method = RequestMethod.POST)
    public Result<?> sync(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = wmsSyncFacade.syncOrderMerge2DO(new HashMap<>());
        return Result.ok(JSON.toJSONString(map));
    }
}
